package event

import (
	"encoding/json"
	"fmt"
	"gitchina/CPTT4WeChat/data"
	"gitchina/CPTT4WeChat/errors"
	"gitchina/CPTT4WeChat/models"
	"gitchina/CPTT4WeChat/models/handle"
)

type ScanCodeEvent struct {
	*PushEvent
	EventKey string
	CodeInfo string
	Type     string
	Result   string
}

type UserId struct {
	Uid string `json:"uid"`
}

func (e *ScanCodeEvent) Handle() interface{} {
	var msg string
	var userId UserId
	if err := json.Unmarshal([]byte(e.Result), &userId); err == nil {
		var usr handle.User
		var w models.WeChat
		if info, ok := w.GetWeChatUserInfo(e.FromUserName); ok {
			if info.Subscribe == 1 {
				if bindOk := usr.Bind(e.FromUserName, userId.Uid, info.NickName); bindOk {
					var u handle.User
					if usr, ok := u.GetByOpenId(e.FromUserName); ok {
						var g handle.Garden
						if garden, ok := g.GetByUid(usr.GetGardenUid()); ok {
							if usr.GetUserType() == 1 {
								msg = fmt.Sprintf("您好: [%s][%s]\n您是管理员，可以查看全园年班出勤信息！", garden.GetName(), usr.GetName())
							} else {
								var repo data.ApiRepo
								if class, ok := repo.GetClassInCharge(usr.GetId()); ok {
									msg = fmt.Sprintf("您好: [%s][%s]\n您是班主任，可以查看[%s]出勤信息！", garden.GetName(), usr.GetName(), class)
								} else {
									msg = fmt.Sprintf("您好: [%s][%s]\n您是普通权限，没有可查看的信息！", garden.GetName(), usr.GetName())
								}
							}
						}
					}
				} else {
					msg = errors.Bind_User_Error
				}
			} else {
				msg = errors.Subscribe_First
			}
		} else {
			msg = errors.Unknown_User
		}
	} else {
		msg = errors.Invalid_QRCode
	}

	return CreateTextResponseMessage(e.WeChatRequestMessage, msg)
}

func (e *ScanCodeEvent) OnParse(params map[string]string) Event {
	e.CodeInfo = params["scancodeinfo"]
	e.Type = "qrcode"
	e.Result = params["scanresult"]
	return e
}
